package com.example.myapplication.repository;

import android.content.Context;
import android.os.AsyncTask;

import androidx.lifecycle.LiveData;

import com.example.myapplication.PersonDatabase;
import com.example.myapplication.dao.PersonDao;
import com.example.myapplication.model.Person;

import java.util.List;

public class PersonRepository {
    private LiveData<List<Person>> allPersonLive;
    private PersonDao personDao;


    public PersonRepository(Context context) {
        PersonDatabase personDatabase=PersonDatabase.getDatabase(context.getApplicationContext());
        personDao=personDatabase.getPersonDao();
        allPersonLive=personDao.findAllLive();
    }

    public LiveData<List<Person>> getAllPersonLive() {
        return allPersonLive;
    }

    public void insertPerson(Person...people){
        new InsertAsyncTask(personDao).execute(people);
    }

    public void deleteAllPerson(Person...people){
        new ClearAllAsyncTask(personDao).execute();
    }


    public static class InsertAsyncTask extends AsyncTask<Person,Void,Void>{
        private PersonDao personDao;

        public InsertAsyncTask(PersonDao personDao) {
            this.personDao = personDao;
        }

        @Override
        protected Void doInBackground(Person... people) {
            personDao.insertPerson(people);
            return null;
        }
    }


    /**
     * 不需要参数
     */
    static class ClearAllAsyncTask extends AsyncTask<Void,Void,Void>{
        private PersonDao personDao;

        public ClearAllAsyncTask(PersonDao personDao) {
            this.personDao = personDao;
        }

        @Override
        protected Void doInBackground(Void...voids) {
            personDao.clear();
            return null;
        }
    }


}
